/*
 * sys_mem.h
 *
 *  Created on: 2017年8月5日
 *      Author: 0yfj0
 */

#ifndef _SYS_MEM_H_
#define _SYS_MEM_H_

#ifdef __cplusplus
extern "C"
{
#endif  /* __cplusplus */
#include <stdint.h>
#include "../../ble_lamp/app/sys_mem_conf.h"

/*----------------------------------------------------------------------------*/
#ifndef MEM_FUNC_TEST
#define MEM_FUNC_TEST	(1)
#endif
#ifndef MEM_MAX_SIZE
#define MEM_MAX_SIZE	(16*1024)
#endif

#ifndef _PTR_T
#define _PTR_T
typedef unsigned long ptr_t;
#endif

/*----------------------------------------------------------------------------*/
int mem_init(void *buff, uint32_t size);
void *mem_malloc(uint32_t size);
void *mem_calloc(uint32_t n, uint32_t size);
void *mem_realloc(void *buff, uint32_t newsize);
void mem_free(void *buff);
#if (MEM_DBG)
void mem_log(char *format, ...);
#else
#define mem_log(...)
#endif
#if (MEM_FUNC_TEST)
void mem_test(void);
#endif

/*----------------------------------------------------------------------------*/
#ifndef MEM_BIT_SIZE
#define MEM_BIT_SIZE	(8)/* 4~32, 4*n */
#endif
/* 31 = 32 - 1
 * i / 32 = i >> 5, i % 32 = i & 31 */
#define mem_flag_unlock(_bit) mem.lock[(_bit)>>5]&=~(1<<((_bit)&31))
#define mem_flag_lock(_bit) mem.lock[(_bit)>>5]|=(1<<((_bit)&31))
#define mem_flag(_bit) (mem.lock[(_bit)>>5]&(1<<((_bit)&31)))
#if (MEM_BIT_SIZE<4||MEM_BIT_SIZE>32)
#error MEM_BIT_SIZE error
#endif
#if (MEM_BIT_SIZE&(MEM_BIT_SIZE-1))
#error MEM_BIT_SIZE error
#endif

#if (MEM_MAX_SIZE==0)
#error MEM_MAX_SIZE error
#endif
#if (MEM_MAX_SIZE/(32*MEM_BIT_SIZE)==0)
#error MEM_MAX_SIZE too small
#endif
typedef struct
{
	ptr_t addr;
	uint32_t size;
	uint32_t lock[MEM_MAX_SIZE / (32 * MEM_BIT_SIZE)];
	uint32_t magic;
} mem_t;

#define MEM_MAGIC (0x5A5A5A5A)
/*----------------------------------------------------------------------------*/

#ifdef __cplusplus
}
#endif  /* __cplusplus */
#endif  // _SYS_MEM_H_
